package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY_PRE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Resource
    private IFollowService followService;

    //根据分页查询热点文章
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户，设置文章用户信息，判断当前用户是否点赞该文章
        records.forEach(blog ->{
            queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    //根据id查询文章
    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        if(blog == null){
            return Result.fail("博客文章不存在！");
        }
        // 2.查询blog有关的用户
        queryBlogUser(blog);
        // 3.查询blog是否被点赞，前端页面的判断来自与这里blog对象中的isLike字段值
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    //判断文章是否被当前用户点赞，设置blog的isLike字段值
    private void isBlogLiked(Blog blog) {

        UserDTO userDTO = UserHolder.getUser();
        if(userDTO != null){
            // 1.获取登录用户
            Long userId = userDTO.getId();
            // 2.判断当前登录用户是否已经点赞
            String key = BLOG_LIKED_KEY + blog.getId();
//          Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
//            Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//          blog.setIsLike(BooleanUtil.isTrue(isMember));
//            blog.setIsLike(score != null);
            Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
            blog.setIsLike(score != null);
        }

    }

//    private void isBlogLiked(Blog blog) {
//                // 1.获取登录用户
//                Long userId = UserHolder.getUser().getId();
//                // 2.判断当前登录用户是否已经点赞
//                String key = BLOG_LIKED_KEY + blog.getId();
//                Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
//                blog.setIsLike(BooleanUtil.isTrue(isMember));
//    }

    //点赞文章,将点赞的用户的id存放至redis中
    @Override
    public Result likeBlog(Long id) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + id;
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //因为isMember是包装类，所以不能直接判断，使用Boolean包装类
        if(score == null){
            //BooleanUtil.isFalse(isMember
            // 3.如果未点赞，可以点赞
            // 3.1数据库点赞数 + 1
            boolean isSuccess = update()
                    .setSql("liked = liked + 1")
                    .eq("id", id).update();
            // 3.2保存用户到Redis的set集合
            if(isSuccess){
//                stringRedisTemplate.opsForSet().add(key,userId.toString());
                //采用时间戳作为member的score，ZADD key score1 member1 [score value ...]
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else{
            // 4.如果已点赞，取消点赞
            // 4.1.数据库点赞数 - 1
            boolean isSuccess = update()
                    .setSql("liked = liked - 1")
                    .eq("id", id).update();
            // 4.2.把用户从Redis的set集合移除
            if(isSuccess){
//                stringRedisTemplate.opsForSet().remove(key,userId.toString());
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    //查询点赞该id笔记的前五名用户信息
    @Override
    public Result queryBlogLikes(Long id) {
        //redis中存放该笔记点赞用户id的集合中的key
        String key = BLOG_LIKED_KEY + id;
        // 1.查询top5的点赞用户 ZRANGE key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            //返回空集合
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 将ids转成以","拼接而成的字符串
        String idsStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户，不能直接返回User，涉及敏感信息，要返回UserDTO
        // SELECT id,phone,password,nick_name,icon,create_time,update_time FROM tb_user WHERE id IN ( ? , ? ) ORDER BY FIELD(id , ?, ?...)
        List<UserDTO> userDTOs = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        /**
         * userService.listByIds(ids) ==>SELECT id,phone,password,nick_name,icon,create_time,update_time FROM tb_user WHERE id IN ( ? , ? )
         */
        // 4.返回
        return Result.ok(userDTOs);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long userId) {
        //根据用户id分页查询用户的博文笔记
        Page<Blog> blogPage = this.query()
                .eq("user_id", userId).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        //获取当前数据
        List<Blog> records = blogPage.getRecords();
        return Result.ok(records);
    }

    //用户发布新的博客笔记，将博客笔记存放至数据以及Redis中，即推送给粉丝的收件箱
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店笔记
        boolean isSuccess = save(blog);
        if(!isSuccess){
            Result.fail("新增笔记失败！");
        }
        // 3.查询笔记作者的所有粉丝，查询set集合或者查询数据库(select * from tb_follow where follow_user_id = ?)
        List<Follow> fans = followService.query()
                .eq("follow_user_id", user.getId()).list();
        // 4.推送笔记id给所有粉丝
        for(Follow fan : fans){
            // 4.1.获取粉丝id
            Long fanId = fan.getUserId();
            // 4.2.推送笔记id给粉丝的收件箱
            String key = FEED_KEY_PRE + fanId;
            Boolean feed = stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5.返回id
        return Result.ok(blog.getId());

    }

    //设置文章的用户相关信息
    private void queryBlogUser(Blog blog) {
        try{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    //分页查询关注用户的博客文章笔记
    @Override
    public Result queryBlogOfFollow(Long minTime, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();

        // 2.查询当前用户的收件箱 ZREVRANGEBYSCORE key max min LIMIT offset count
        String key = FEED_KEY_PRE + userId;
        /**
         * public interface TypedTuple<V> extends Comparable<ZSetOperations.TypedTuple<V>> {
         *         @Nullable
         *         V getValue();
         *
         *         @Nullable
         *         Double getScore();
         *     }
         */
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, minTime, offset, 2); // key min max offset count
        // 3.非空判断
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 4.解析数据：包含blogId、minTime时间戳、offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size()); //当前页数的笔记id
        long min = 0L; //当前页数的笔记最小时间戳
        Integer os = 1; //计算score最小时间戳的元素个数
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples){ // 5 4 4 2 2
            // 4.1.获取Blog的id
            String blogId = tuple.getValue();
            blogIds.add(Long.valueOf(blogId));
            // 4.2.获取时间戳
            long time = tuple.getScore().longValue();
            // 4.3.判断当前时间戳是否跟min上一个时间戳相同
            if(time == min){
                //最小时间戳不变，os自增1
                os++;
            }else{
                min = time;
                os = 1; //重置是因为最小时间戳重复的元素在分页的中间，因此需要重置
            }
        }

        // 4.根据id查询blog，利用MP封装的函数
        //List<Blog> blogList = listByIds(blogIds); //但这种是基于IN(?,?,?)来查的，不能保证顺序，跟点赞排行榜一样
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogList = query().
                in("id", blogIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 4.1.设置blog的相关信息
        for (Blog blog : blogList) {
            // 4.1.1查询blog相关的用户
            queryBlogUser(blog);
            // 4.1.2判断笔记是否被当前用户点赞
            isBlogLiked(blog);
        }
        
        // 5.封装并返回
        ScrollResult result = new ScrollResult();
        result.setList(blogList);
        result.setMinTime(min);
        result.setOffset(os);
        return Result.ok(result);
    }
}
